<template>
  <div class="app-container home">
    <!--   待办 -->
    <div class="home-left">
      <div class="home-left_info">
        <!-- 用户信息 -->
        <div class="home-left_user">
          <div class="user-avatar">
            <a-image class="avatar-img" :preview="false" :src="avatarUrl" width="88px" height="88px"></a-image>
          </div>
          <div class="user-name">{{ userStore.name }}</div>
          <div class="user-dept">{{ userStore.mainDeptName }} | {{ userStore.userPost }}</div>
        </div>
        <!-- 审批流程/消息 start -->
        <div class="approve-msg">
          <div class="approve-msg__options">
            <!--          审批/消息切换 start  -->
            <div class="approve-msg__options__tabs">
              <div
                v-for="item in auditAndMessageType"
                :key="item.value"
                @click="changeApproveMsgTab(item.value as any)"
                class="tabs-item"
                :class="{ 'tabs-item--active': approveMsgType === item.value }"
              >
                <a-badge :max-count="10" :count="item.count">
                  {{ item.label }}
                </a-badge>
              </div>
            </div>
            <!--       审批/消息切换 end     -->
            <!--         状态切换 start   -->
            <div class="approve-msg__options__buttons">
              <div
                v-for="item in statusList"
                :key="item.value"
                @click="changeMessageStatus(item.value)"
                class="button-item"
                :class="{ 'button-item--active': auditMsgStatus === item.value }"
              >
                {{ item.label }}
                <span>({{ item.count }})</span>
              </div>
            </div>
            <!--         状态切换 end   -->
          </div>
          <component
            ref="auditAndMsgRef"
            :is="msgAuditCom"
            :filter-tab="filterTab"
            :audit-msg-status="auditMsgStatus"
            @changeFilterTab="changeFilterTab"
            @drawerMsgCancel="handleCloseMsgDrawer"
          ></component>
        </div>
        <!-- 审批流程/消息 end  -->
      </div>
      <!-- 待办任务列表 -->
      <Todo />
    </div>
    <!--  任务排期  -->
    <div class="app-container task-scheduling">
      <Calendar />
    </div>
    <!--  修改初始密码  充值提醒  -->
    <teleport to="body">
      <template v-if="isShowModal">
        <div class="custom-modal-mask"></div>
        <div class="custom-modal-body">
          <div class="recharge-container" v-if="isRecharge">
            <a-image class="recharge-icon" :preview="false" :src="RechargeIcon" width="130" height="130"></a-image>
            <div class="tip-content">
              {{ userStore.nowTenantName }}，我们提供的服务将于{{ expiredTime }}到期，请管理员联系客服缴纳费用
            </div>
            <a-button type="primary" @click="handleCloseRecharge">我知道了</a-button>
          </div>
          <!--      首次登录修改初始密码 start    -->
          <div class="set-password" v-if="isInitPassword">
            <div class="set-password_icon">
              <a-image :src="pwdSet" width="116px" height="116px"></a-image>
              <div class="set-password_tip">首次登录请修改初始密码~</div>
            </div>
            <a-form
              ref="initPasswordRef"
              :model="initPasswordForm"
              :rules="iniTFormRules"
              :label-col-style="{ display: 'none' }"
              :wrapper-col-style="{ flex: 1 }"
              @submit="handelSetPassword"
            >
              <a-form-item field="password" style="margin-bottom: 15px">
                <a-input-password v-model.trim="initPasswordForm.password" placeholder="请输入新密码" />
              </a-form-item>
              <a-form-item field="checkPassword" style="margin-bottom: 0">
                <a-input-password v-model.trim="initPasswordForm.checkPassword" placeholder="请输入确认密码" />
              </a-form-item>
              <div class="set-password_form-tip">密码至少6位数，支持数字、字母和除空格外的特殊字符</div>
              <a-button class="login-btn" html-type="submit">确认修改</a-button>
            </a-form>
          </div>
          <div class="set-password_success" v-if="isInitPasswordSuccess">
            <div class="set-password_success-icon">
              <a-image :preview="false" :src="pwdSuccess" width="100px" height="100px"></a-image>
              <div class="set-password_success-tip">修改成功~</div>
            </div>
          </div>
        </div>
      </template>
    </teleport>
    <OpenAccount v-model="isOpenAccount" />
  </div>
</template>

<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import Todo from "./components/Todo.vue";
import Calendar from "./components/Calendar.vue";
import MessageList from "./components/components/messageList/index.vue";
import AuditList from "./components/components/auditList/index.vue";
import { useUserStore } from "@/stores";
import { getLocalCache, setLocalCache } from "@/utils/cache";
import { changePassword, workbenchMsgNumber } from "@/apis";
import type { ProcessCount, MessageCount, WorkbenchMsgListParams, CategoryType, MessageType } from "@/apis";
import * as config from "./config";
import type { ConfigItem } from "@/views/home/types";
import RechargeIcon from "@/assets/images/recharge-icon.png";
import Avatar from "@/assets/images/default-avatar.png";
import pwdSet from "@/assets/images/pwd-set.png";
import pwdSuccess from "@/assets/images/pwd-set-success.png";
import { useStorage } from "@vueuse/core";

const openAccountStatus = useStorage("openAccountStatus", {
  number: 0,
  expirationTimestamp: 0
});
defineOptions({ name: "Home" });
const { proxy }: any = getCurrentInstance();

const userStore = useUserStore();

const avatarUrl = computed(() => {
  return userStore.avatar || Avatar;
});
const isOpenAccount = ref(false); // 打开开户弹窗
const isShowModal = ref(false);

/**
 * 审批&消息
 */
// 审批/消息
const auditAndMsgRef = ref<any>(null);
const auditAndMessageType = ref([...config.auditAndMessageType]);
const approveMsgType = ref<string>("audit");
type tabType = "message" | "audit";
const changeApproveMsgTab = (tabType: tabType) => {
  if (tabType === approveMsgType.value) return;
  approveMsgType.value = tabType;
  auditMsgStatus.value = "untreated";
  const configMap: Record<string, [string, Array<ConfigItem>]> = {
    audit: ["processAccept", config.auditStatus],
    message: ["msgAccept", config.messageStatus]
  };
  configMap[tabType] && ([filterTab.value as any, statusList.value] = configMap[tabType]);
  getAuditAndMsgData();
};
const msgAuditCom = computed(() => {
  return approveMsgType.value === "audit" ? AuditList : MessageList;
});
// 状态按钮列表
const statusList = ref<any[]>([...config.auditStatus]);
// 当前状态 默认待审批
const auditMsgStatus = ref<MessageType>("untreated");
const changeMessageStatus = async (state: MessageType) => {
  getAuditAndMsgList(state);
};
// 列表数据分类切换 默认我审批的
const filterTab = ref<CategoryType>("processAccept");
const changeFilterTab = (type: CategoryType) => {
  filterTab.value = type;
  getAuditAndMsgData();
};
// 审批&消息数量
const badgeCount = (process: ProcessCount, msg: MessageCount) => {
  //需要我审批的
  auditAndMessageType.value[0].count = process?.acceptUntreated ?? 0;
  // 需要我处理的
  auditAndMessageType.value[1].count = msg?.acceptUntreated ?? 0;
};
// 状态按钮数值
type DataSources = {
  [key in "audit" | "message"]: {
    [key: string]: (() => number)[];
  };
};
const statusCount = (process: ProcessCount, msg: MessageCount) => {
  const dataSources: DataSources = {
    audit: {
      processAccept: [() => process?.acceptAll ?? 0, () => process?.acceptUntreated ?? 0, () => process?.acceptTreated ?? 0],
      processSend: [() => process?.sendAll ?? 0, () => process?.sendUntreated ?? 0, () => process?.sendTreated ?? 0]
    },
    message: {
      msgAccept: [() => msg?.acceptUnread ?? 0, () => msg?.acceptUntreated ?? 0, () => msg?.acceptAndTreatedNum ?? 0],
      msgSend: [() => msg?.sendUnread ?? 0, () => msg?.sendUntreated ?? 0, () => msg?.sendReadAndTreatedNum ?? 0]
    }
  };
  const updateStatusList = (type: "audit" | "message", tab: string): void => {
    const handlers = dataSources[type]?.[tab];
    if (handlers) {
      handlers.forEach((handler, index) => {
        statusList.value[index].count = handler();
      });
    }
  };
  updateStatusList(approveMsgType.value as tabType, filterTab.value);
};
// 加载数据
const getWorkbenchMsgNumber = async () => {
  const {
    data: { process, msg }
  } = await workbenchMsgNumber();
  badgeCount(process, msg);
  statusCount(process, msg);
};
const getAuditAndMsgList = async (state: MessageType) => {
  await nextTick();
  auditMsgStatus.value = state;
  const params: WorkbenchMsgListParams = {
    current: 1,
    size: 3,
    category: filterTab.value,
    type: state
  };
  const getListData = auditAndMsgRef.value.getWorkbenchMsgList;
  getListData(params);
};
const getAuditAndMsgData = () => {
  getAuditAndMsgList(auditMsgStatus.value);
  getWorkbenchMsgNumber();
};
// 关闭消息操作弹窗
const handleCloseMsgDrawer = (isRefresh: boolean) => {
  isRefresh && getAuditAndMsgData();
};

/**
 * 首次登录强制修改密码
 */
const isInitPassword = ref(false);
const isInitPasswordSuccess = ref(false);
const initPasswordForm = ref({
  password: "",
  checkPassword: ""
});
// 校验
type ValidatorCallback = (message: string) => void;
type ValidatorFunction = (value: string, callback: ValidatorCallback) => void;
const validatorPassword: ValidatorFunction = (value, callback) => {
  const passwordRegex = /^[0-9a-zA-Z\W_].{5,}$/;
  if (value === "") {
    return callback("请输入密码");
  } else if (value.length < 6) {
    return callback("密码至少6位数");
  } else if (!passwordRegex.test(value)) {
    return callback("密码至少6位数，支持数字、字母和除空格外的特殊字符");
  }
};
const validatorCheckPassword: ValidatorFunction = (value, callback) => {
  if (value === "") {
    return callback("请再次输入密码");
  } else if (value !== initPasswordForm.value.password) {
    return callback("两次输入密码不一致");
  }
};
const iniTFormRules = {
  password: [{ required: true, message: "请输入新密码" }, { validator: validatorPassword }],
  checkPassword: [{ required: true, message: "请再次输入密码" }, { validator: validatorCheckPassword }]
};
const handelSetPassword = async () => {
  const valid = await proxy.$refs.initPasswordRef?.validate();
  if (valid) return;
  await changePassword(initPasswordForm.value);
  resetInitForm();
  isInitPassword.value = false;
  isInitPasswordSuccess.value = true;
  userStore.getInfo();
  setTimeout(() => {
    isShowModal.value = false;
    isInitPasswordSuccess.value = false;
  }, 2000);
  Message.success("修改成功");
};
const resetInitForm = () => {
  proxy.$refs.initPasswordRef.resetFields();
  initPasswordForm.value = {
    password: "",
    checkPassword: ""
  };
};
/**
 * 充值提醒
 */
const isRecharge = ref(false);
const expiredTime = ref(userStore.expiredTime);
const handleCloseRecharge = () => {
  isRecharge.value = false;
  isShowModal.value = false;
  if (userStore.userInfo.isDefaultPassword) {
    isShowModal.value = true;
    isInitPassword.value = true;
  }
};

/**
 * 检查是否到期
 */
if (userStore.isExpired && !getLocalCache("expired")) {
  isShowModal.value = true;
  isRecharge.value = true;
  setLocalCache("expired", "true");
} else {
  if (userStore.userInfo.isDefaultPassword) {
    isShowModal.value = true;
    isInitPassword.value = true;
  }
}
const getTodayEndTimestamp = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth();
  const date = now.getDate();
  // 创建一个新的 Date 对象，设置时间为 23:59:59
  const endOfDay = new Date(year, month, date, 23, 59, 59);
  // 获取时间戳
  return endOfDay.getTime();
};

const setOpenAccountModalShow = () => {
  if (!userStore.isTenantMaster) {
    isOpenAccount.value = false;
    return;
  }
  if (!openAccountStatus.value.expirationTimestamp) {
    openAccountStatus.value.expirationTimestamp = getTodayEndTimestamp();
  }
  if (Date.now() > openAccountStatus.value.expirationTimestamp) {
    openAccountStatus.value.expirationTimestamp = getTodayEndTimestamp();
    openAccountStatus.value.number = 0;
    isOpenAccount.value = !userStore.openFinanceAccount;
  } else {
    if (openAccountStatus.value.number >= 3) {
      isOpenAccount.value = false;
    } else {
      isOpenAccount.value = !userStore.openFinanceAccount;
    }
  }
  if (isOpenAccount.value) {
    openAccountStatus.value.number += 1;
  }
};
onMounted(() => {
  setOpenAccountModalShow();
  getWorkbenchMsgNumber();
  getAuditAndMsgList("untreated");
});
</script>

<style lang="scss" scoped>
@import "index";
</style>
